<?php
/**
 * 买单付款
 */
namespace app\ais\controller\api\v1;
use app\ais\controller\api\Base;
use app\ais\model\AisOrder;
use app\ais\model\AisStore;
use app\ais\model\AisCoupon;
use app\ais\model\AisCouponUser;
use app\ais\model\AisConfig;
use app\common\facade\WechatPay;
use app\common\model\SystemUserLevel;
use think\Db;

class Storepay extends Base{

    protected $config;

    /**
     * 初始化当前应用管理员是不是联盟城市账户
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
        $this->config = AisConfig::getConfig($this->member_miniapp_id);
    }

    /**
    * 读取买单商家信息和优惠券
    * @return void
    */
    public function index(){
        $param['store_id']  = $this->request->param('store_id/d');
        $param['chain_id']  = $this->request->param('chain_id/d');
        $this->apiSign($param);
        if(empty($param['store_id'])){
            return enjson(404,'为找到付款好店');
        }
        $store = AisStore::where(['is_lock' => 0,'id' => $param['store_id']])->field('id,name')->find();
        if(empty($store)){
            return enjson(303,'未找到付款好店',['url' =>'/pages/index']);
        }
        if(!empty($param['chain_id'])){
            $store = $store->chain()->where('id',$param['chain_id'])->field('id,title,store_id')->find();
            if(empty($store)){
                return enjson(303,'未找到付款分店',['url' =>'/pages/index']);
            }
            $store->name     = $store->title;
            $store->chain_id = $store->id;
            $store->id       = $store->store_id;
        }
        $is_get_coupon = 0;
        if(empty($this->config->is_pay_open_coupon)){
            $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
            $condition[] = ['uid','=',$this->user->id];
            $condition[] = ['is_end','=',0];
            $condition[] = ['money','=',0];
            $condition[] = ['store_id','=',$param['store_id']];
            $coupon = AisCouponUser::where($condition)->field('id,name,tips,howmuch,store_id,price,types,coupon_id,discount,create_time')->order('create_time desc')->select();
            foreach ($coupon as $key => $value){
                $coupon[$key]->is_get_coupon = 0;
                $coupon[$key]->end_time      = $this->config->coupon_longtime * 60 * 60;
            }
        }else{
            $coupon = AisCoupon::where(['member_miniapp_id' => $this->miniapp_id,'store_id' => $param['store_id'],'is_lock' => 0,'is_end' => 0])->order('is_top desc,sort desc,create_time desc')->select();
            foreach ($coupon as $key => $info){
                $coupon[$key]->end_time      = $info->create_time + $this->config->coupon_longtime * 60 * 60;
                $coupon[$key]->is_get_coupon = 0; 
            }
            $is_get_coupon = 1;
        }
        return enjson(200,['coupon' => $coupon ,'store' => $store,'is_get_coupon' => $is_get_coupon]);
    }


    /**
     * 根据定位推荐附近同圈子的优惠券
     * @return void
     */
    public function couponTop(){
        $param['store_id']  = $this->request->param('store_id/d',0);   //来自哪个商家
        $this->apiSign($param);
        $store = AisStore::where(['member_miniapp_id' => $this->miniapp_id,'id' => $param['store_id'],'is_lock' => 0])->find();
        if(empty($store)){
            return enjson(204);
        }
        if(empty($this->lbs->lat) || empty($this->lbs->lng)){
            return enjson(204);
        }
        $prefix = config('database.prefix');
        $latitude  = $this->lbs->lat;
        $longitude = $this->lbs->lng;
        $sql = 'select id,img,name from '.$prefix.'Ais_store where latitude > '.$latitude .'-1 and latitude < '.$latitude .'+1 and longitude > '.$longitude.'-1 and longitude < '.
            $longitude.'+1 %s and id != '.$param['store_id'].' order by ACOS(SIN(('.$latitude .' * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 ) +COS(('.$latitude .
            ' * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) *COS(('.$longitude.'* 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380 asc limit 20';
        $ex = 'and id in(select store_id from  '.$prefix.'Ais_store_union where group_id in (select group_id from '.$prefix.'Ais_store_union where member_miniapp_id = '.$this->miniapp_id.' and store_id = '.$param['store_id'].
            ' and type = 0 )  and type = 0 )';
        $unionList = Db::query(sprintf($sql,$ex)); //附近商圏店铺查询
        if(count($unionList) == 0){
            $ex = 'and cate_id = '. $store->cate_id;
            $unionList = Db::query(sprintf($sql,$ex));   //附近同行业店铺查询
        }
        if(count($unionList) == 0){
            $unionList = Db::query(sprintf($sql,''));  //附近店铺查询
        }
        $store = [];
        foreach($unionList as $key => $val){ 
            $store[$val['id']] = $val;
        } 
        $store_ids =  implode(',',array_column($unionList,'id'));
        $list = Db::query('SELECT * FROM '.$prefix.'Ais_coupon WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM '.$prefix.'Ais_coupon)-(SELECT MIN(id) FROM '.$prefix.'Ais_coupon)) + (SELECT MIN(id) FROM '.$prefix.'Ais_coupon))) and member_miniapp_id = '.
            $this->miniapp_id.' and is_lock = 0 and is_end = 0 and store_id in ('.$store_ids.') ORDER BY id LIMIT 15;');
        if (count($list)) {
            return enjson(200,'success',['coupon' => $list,'store' => $store]);
        }
        return enjson(204);
    }
    
    /**
     * 微信给商家支付
     * @param string $no
     * @return void
     */
    public function wechat(){
        if (request()->isPost()) {
            $rule = [
                'member_miniapp_id' => $this->miniapp_id,
                'store_id'          => $this->request->param('store_id/d'),
                'chain_id'          => $this->request->param('chain_id/d',0),
                'user_couponr_id'   => $this->request->param('user_couponr_id/d',0),
                'money'             => $this->request->param('money/f'),
                'amount'            => $this->request->param('amount/f'),
                'uid'               => $this->user->id,
            ];
            $validate = $this->validate($rule,'Dopay.gopay');
            if (true !== $validate) {
                return enjson(204,$validate);
            }
            //判断好店
            $store = AisStore::where(['member_miniapp_id' => $this->miniapp_id,'id' => $rule['store_id'],'is_lock' => 0])->find();
            if(empty($store)){
                return enjson(204,'未找到商户');
            }
            $store->chain_id = 0;
            if(!empty($rule['chain_id'])){
                $chain = $store->chain()->where('id',$rule['chain_id'])->field('id,title,store_id')->find();
                if(empty($chain)){
                    return enjson(204,'未找到付款分店');
                }
                $store->title = $chain->title;
                $store->chain_id = $chain->id;
            }
            if(empty($store->manage_uid)){
                return enjson(204,'未设置老板');
            }
            if(empty($store->mch_id)){
                return enjson(204,'未找到商家微信商户号');
            }
            //计算付款金额
            $amount = AisOrder::countPrice($rule);
            if(!$amount){
                return enjson(204,'优惠券不满足使用条件');
            }
            //创建订单
            $order_no = order_no($this->user->invite_code);
            //唤醒微信支付参数
            $payparm = [
                'openid'     => $this->user->miniapp_uid,
                'miniapp_id' => $this->miniapp_id,
                'name'       => $store->name,
                'order_no'   => $order_no,
                'attach'     => 'Y',
                'total_fee'  => $amount['price'] * 100,
                'notify_url' => api(1,'ais/notify/storePay', $this->miniapp_id),
            ];
            $payparm['mchid'] = $store->mch_id;
            if(!empty($amount['coupon'])){
                if($amount['coupon']->parent_store_id > 0){
                    $rule['parent_store_id']   = $amount['coupon']->parent_store_id;  //引荐的店铺
                    $payparm['profit_sharing'] = 'Y';
                    $payparm['attach']         = 'Y';
                }
                $rule['coupon_cache'] = $amount['coupon'];    //优惠券
            }
            $level = SystemUserLevel::where(['user_id' => $this->user->id,'level' => 1])->find();
            if($level && $level->parent_id != $store->manage_uid){
                $payparm['profit_sharing'] = 'Y';
                $payparm['attach']         = 'Y';
            }
            $ispay = WechatPay::orderPay($payparm);
            if($ispay['code'] == 0){
                return enjson(204,$ispay['msg']);
            }
            //添加订单记录
            $rule['order_no']       = $order_no;
            $rule['price']          = $amount['price'];    //实际金额
            $rule['store_chain_id'] = $store->chain_id;    //分店ID
            $rel = AisOrder::addOrder($rule);
            if(!$rel){
                return enjson(204,'订单创建失败');
            }
            return enjson(200,'成功',$ispay['data']);
        }
    }

}